<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类数据设置参数"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 栅格布局分类选择 -->
      <el-row class="cate_opt">
        <el-col>
          <div>
            <span>选择商品分类:</span>
            <!-- 显示级联选择器 -->
            <el-cascader
              v-model="selectedKeys"
              :options="cateList"
              :props="cascaderProps"
              clearable
              @change="changeCate"
            ></el-cascader>
          </div>
        </el-col>
      </el-row>

      <!-- 表格数据主体 -->
      <el-tabs
        v-model="activeName"
        @tab-click="changeTab"
      >
        <!-- 对于用户来说，参数是活的，可以选择的，属性是死的，只能阅读的 -->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="btnCtrl"
            @click="addPropData"
          >添加参数</el-button>
          <!-- 要展示的属性表格 -->
          <el-table
            :data="manyData"
            border
            stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTag(i, scope.row)"
                >{{ item }}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editPropData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delPropData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="btnCtrl"
            @click="addPropData"
          >添加属性</el-button>
          <!-- 要展示的属性表格 -->
          <el-table
            :data="onlyData"
            border
            stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTag(i, scope.row)"
                >{{ item }}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editPropData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delPropData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性、参数的对话框 -->
    <el-dialog
      :title="'修改' + addPropInfo"
      :visible.sync="addPropDialog"
      width="50%"
      @close="closeAddProp"
    >

      <!-- 显示输入的表单 -->
      <el-form
        :model="addProp"
        :rules="addPropRules"
        ref="addPropRef"
        label-width="100px"
      >
        <el-form-item
          :label="addPropInfo"
          prop="attr_name"
        >
          <el-input v-model="addProp.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addPropDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addPropCtrl"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑属性、参数的对话框 -->
    <el-dialog
      :title="'编辑' + addPropInfo"
      :visible.sync="editPropDialog"
      width="50%"
      @close="closeAddProp"
    >

      <!-- 显示输入的表单 -->
      <el-form
        :model="editProp"
        :rules="addPropRules"
        ref="addPropRef"
        label-width="100px"
      >
        <el-form-item
          :label="addPropInfo"
          prop="attr_name"
        >
          <el-input v-model="editProp.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editPropDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editPropCtrl"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedKeys: [],
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
        // checkStrictly: false
      },
      activeName: 'many',
      manyData: [],
      onlyData: [],
      addPropDialog: false,
      // 添加参数的数据控制
      addProp: {
        attr_name: ''
      },
      // 添加参数的规则控制
      addPropRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 编辑属性/参数的对话框系列
      editPropDialog: false,
      editProp: {
        attr_name: ''
      },
      editId: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.cateList = res.data
    },
    // 级联选框切换的方法
    changeCate() {
      // 当选择的分类不是三级分类的时候，直接返回空数组
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = this.manyData = this.onlyData = []
        return
      }
      this.getParamsList()
    },
    async getParamsList() {
      // 发起请求，需要使用计算方法中的id，返回动态的id值，传入对应的参数（后台要求的值）
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('请求数据失败')

      // 1.0 把请求回来的数据，字符串转换成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)

      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 选项卡切换的数据
    changeTab() {
      this.getParamsList()
    },
    addPropData() {
      this.addPropDialog = true
    },
    closeAddProp() {
      this.$refs.addPropRef.resetFields()
    },
    addPropCtrl() {
      this.$refs.addPropRef.validate(async valid => {
        if (!valid) return
        // 发起请求，需要使用计算方法中的id，返回动态的id值，传入对应的参数（后台要求的值）
        let { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            // 这里的参数是 添加数据控制中的属性
            attr_name: this.addProp.attr_name,
            // 这里的值是tab选项卡切换的属性值
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        // 重新获取数据
        this.getParamsList()
        this.addPropDialog = false
      })
    },
    async editPropData(id) {
      this.editId = id
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // 将获取到的数据指定在data中，页面的表单就能渲染
      this.editProp.attr_name = res.data.attr_name
      // 将对应属性id存储在data中，方便修改请求的时候添加
      this.editId = res.data.attr_id
      this.editPropDialog = true
    },
    editPropCtrl() {
      this.$refs.addPropRef.validate(async valid => {
        if (!valid) return
        // 发起请求，需要使用计算方法中的id，返回动态的id值，传入对应的参数（后台要求的值）
        let { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editId}`,
          {
            // 这里的参数是 添加数据控制中的属性
            attr_name: this.editProp.attr_name,
            // 这里的值是tab选项卡切换的属性值
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        // 重新获取数据
        this.getParamsList()
        this.editPropDialog = false
      })
    },
    async delPropData(id) {
      // 1.0 处理提示的内容 confirm
      let resText = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (resText !== 'confirm') return this.$message.info('取消删除了')

      // 2.0  发起删除的请求，填入两个id
      let { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      // 重新获取数据
      this.getParamsList()
    },
    showInput(row) {
      row.inputVisible = true
      // $nextTick 由于当上面的值变成true之后，并不代表页面就有元素了
      // 它的作用就是等待页面重新渲染完毕之后，才会执行内部代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      // 如果是一堆空格，就不做任何处理
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 1.0 在页面中创建新的tag标签
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.saveAttr(row)
    },
    async saveAttr(row) {
      // 2.0 发起请求，同步更新数据
      let { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('修改参数项成功')
    },
    async closeTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr(row)
    }
  },
  computed: {
    btnCtrl() {
      if (this.selectedKeys.length !== 3) return true
      return false
    },
    cateId() {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    addPropInfo() {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin: 20px 0;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 120px;
}
</style>